package com.ming_za.odupdaterserver.core.service.res;

import com.ming_za.odupdaterserver.api.LocalFileResReader;
import com.ming_za.odupdaterserver.api.ResourcesManager;
import com.ming_za.odupdaterserver.core.config.ConfigManager;
import com.ming_za.odupdaterserver.core.config.type.IntValue;
import com.ming_za.odupdaterserver.core.service.res.obj.LocalResItem;
import com.ming_za.odupdaterserver.core.thread.BlockExecuteTreadPool;
import com.ming_za.odupdaterserver.core.utils.Msg;
import com.ming_za.odupdaterserver.core.vo.req.ResAddVo;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

@Service
public class LocalFileResReaderImpl implements LocalFileResReader {

    private volatile String fileParent;
    private final ResourcesManager resourcesManager;
    private final Random random;
    private final Msg msg;

    private final IntValue taskConcurrentCount;

    public LocalFileResReaderImpl(ResourcesManager resourcesManager, Random random, Msg msg, ConfigManager configManager) {
        this.resourcesManager = resourcesManager;
        this.random = random;
        this.msg = msg;
        this.taskConcurrentCount = configManager.getTaskConcurrentCount();
    }

    //选中资源文件夹提示
    private final String[] errorSelectFoldTips = {
            "你是认真的？",
            "你想让你的计算机死机？",
            "你真是脑洞大开!",
            "玩够了没？",
            "你想干啥？",
            "你这是在开玩笑？",
            "这样做很好玩吗？",
            "你**想死啊？！",
            "你可真够无聊的",
            "你是故意的？"
    };

    private boolean isReading = false;
    private BlockExecuteTreadPool blockExecuteTreadPool;

    private final AtomicInteger resAddCount = new AtomicInteger(0);

    @Override
    public void readRes(String path, Consumer<LocalResItem> readFunc) {

        if (isReading){
            msg.soutMsg("&6当前已有任务在读取");
            return;
        }

        File resFold = resourcesManager.getResFold();

        try {
            if (checkResFold(new File(path), resFold)) {
                return;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        isReading = true;

        blockExecuteTreadPool = new BlockExecuteTreadPool(taskConcurrentCount.getValue(),taskConcurrentCount.getValue());

        new Thread(() -> {

            File file = new File(path);

            if (!file.exists()) {
                Msg.getInstance().error("文件不存在！");
            }

            if (!resFold.exists()){
                resFold.mkdirs();
            }

            fileParent = file.getParent();

            resAddCount.set(0);

            try {
                readFold(file, readFunc, resFold);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            try {
                blockExecuteTreadPool.awaitTerminationAndShutdown(Long.MAX_VALUE, TimeUnit.DAYS);
                isReading = false;
                msg.info("===========================资源添加完成===========================");
                msg.info("共" + resAddCount.get() + "个");
                blockExecuteTreadPool = null;
            } catch (InterruptedException ignored) {

            }

        }).start();
    }

    private boolean checkResFold(File file,File resFoldPath) throws IOException {
        if (file.isDirectory()) {
            if (resFoldPath.getCanonicalPath().equals(file.getCanonicalPath())){
                //检测选择的是否为存储资源数据的文件夹
                Msg.getInstance().soutMsg("&c" + errorSelectFoldTips[random.nextInt(errorSelectFoldTips.length)]);
                return true;
            }
        }else {
            if(resFoldPath.getCanonicalPath().equals(file.getParentFile().getCanonicalPath())){
                Msg.getInstance().soutMsg("&c无法选择存储资源数据的文件");
                return true;
            }
        }
        return false;
    }

    private void readFold(File fold, Consumer<LocalResItem> readFunc, File resFold) throws IOException {

        if (fold.isDirectory()) {
            File[] files = fold.listFiles();
            if (files != null){
                for (File f : files) {
                    if (checkResFold(f, resFold)){
                        Msg.getInstance().error("=============警告=============");
                        Msg.getInstance().error("发现资源数据存储路径！");
                        Msg.getInstance().error(f.getAbsolutePath());
                        Msg.getInstance().error("已为您跳过");
                        Msg.getInstance().error("=============警告=============");
                        continue;
                    }
                    readFold(f, readFunc,resFold);
                }
            }
        }else {
            ResAddVo resAddVo = new ResAddVo(fold.getPath().replace(fileParent,"."), true,false,0L);
            LocalResItem localResItem = new LocalResItem(resAddVo,fold);
            //异步调用
            try {
                blockExecuteTreadPool.execute(()->{
                    readFunc.accept(localResItem);
                    resAddCount.getAndIncrement();
                });
            } catch (InterruptedException ignored) {
            }
        }
    }
}
